{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Using Astropy Quantities and Units for astrophysical calculations\n",
    "\n",
    "## Authors\n",
    "Ana Bonaca, Erik Tollerud, Jonathan Foster, Lia Corrales, Kris Stern, Stephanie T. Douglas\n",
    "\n",
    "## Learning Goals\n",
    "* Use `Quantity` objects to estimate a hypothetical galaxy's mass\n",
    "* Take advantage of constants in the `astropy.constants` library\n",
    "* Print formatted unit strings\n",
    "* Plot `Quantity` objects with unit labels, using `astropy.visualization.quantity_support`\n",
    "* Do math with `Quantity` objects\n",
    "* Convert quantities with `astropy.units`\n",
    "* Convert between wavelength and energy with `astropy.units.spectral` equivalencies\n",
    "* Use the small angle approximation with `astropy.units.dimensionless_angles` equivalencies\n",
    "* Write functions that take `Quantity` objects instead of numpy arrays\n",
    "* Make synthetic radio observations\n",
    "* Use `Quantity` objects such as data cubes to facilitate a full derivation of the total mass of a molecular cloud\n",
    "\n",
    "## Keywords\n",
    "units, radio astronomy, data cubes, matplotlib\n",
    "\n",
    "## Companion Content\n",
    "[Tools for Radio Astronomy](https://www.springer.com/gp/book/9783662053942) by Rohlfs & Wilson\n",
    "\n",
    "## Summary\n",
    "\n",
    "In this tutorial we present some examples showing how Astropy's `Quantity` object can make astrophysics calculations easier. The examples include calculating the mass of a galaxy from its velocity dispersion and determining masses of molecular clouds from CO intensity maps. We end with an example of good practices for using quantities in functions you might distribute to other people.\n",
    "\n",
    "For an in-depth discussion of `Quantity` objects, see the [astropy documentation section](http://docs.astropy.org/en/stable/units/quantity.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preliminaries"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We start by loading standard libraries and set up plotting for ipython notebooks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# You shouldn't use the `seed` function in real science code, but we use it here for example purposes.\n",
    "# It makes the \"random\" number generator always give the same numbers wherever you run it.\n",
    "np.random.seed(12345)\n",
    "\n",
    "# Set up matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It's conventional to load the Astropy `units` module as the variable  `u`, demonstrated below.  This will make working with `Quantity` objects much easier. \n",
    "\n",
    "Astropy also has a `constants` module where typical physical constants are available.  The constants are stored as objects of a subclass of `Quantity`, so they behave just like a `Quantity`. Here, we'll only need the gravitational constant `G`, Planck's constant `h`, and Boltzmann's constant, `k_B`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import astropy.units as u\n",
    "from astropy.constants import G, h, k_B"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will also show an example of plotting while taking advantage of the `astropy.visualization` package, which provides support for `Quantity` units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from astropy.visualization import quantity_support"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Galaxy mass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this first example, we will use `Quantity` objects to estimate a hypothetical galaxy's mass, given its half-light radius and radial velocities of stars in the galaxy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's assume that we measured the half-light radius of the galaxy to be 29 pc projected on the sky at the distance of the galaxy. This radius is often called the \"effective radius\", so we'll store it as a `Quantity` object with the name `Reff`. The easiest way to create a `Quantity` object is by multiplying the value with its unit. Units are accessed as u.\"unit\", in this case u.pc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Reff = 29 * u.pc"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A completely equivalent (but more verbose) way of doing the same thing is to use the `Quantity` object's initializer, demonstrated below.  In general, the simpler form (above) is preferred, as it is closer to how such a quantity would actually be written in text.  The initalizer form has more options, though, which you can learn about from the [astropy reference documentation on Quantity](http://docs.astropy.org/en/stable/api/astropy.units.quantity.Quantity.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Reff = u.Quantity(29, unit=u.pc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can access the value and unit of a `Quantity` using the `value` and `unit` attributes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"\"\"Half light radius\n",
    "value: {0}\n",
    "unit: {1}\"\"\".format(Reff.value, Reff.unit))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `value` and `unit` attributes can also be accessed within the print function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"\"\"Half light radius\n",
    "value: {0.value}\n",
    "unit: {0.unit}\"\"\".format(Reff))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Furthermore, we can convert the radius in parsecs to any other unit of length using the ``to()`` method. Here, we convert it to meters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"{0:.3g}\".format(Reff.to(u.m)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we'll first create a synthetic dataset of radial velocity measurements, assuming a normal distribution with a mean velocity of 206 km/s and a velocity dispersion of 4.3 km/s."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vmean = 206\n",
    "sigin = 4.3\n",
    "v = np.random.normal(vmean, sigin, 500)*u.km/u.s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"\"\"First 10 radial velocity measurements: \n",
    "{0}\n",
    "{1}\"\"\".format(v[:10], v.to(u.m/u.s)[:10]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One can ocassionally run into issues when attempting to plot `Quantity` objects with `matplotlib` libraries. It is always possible to fix this by passing the value array (e.g., `v.value`) to `matplotlib` functions. However, calling the `astropy.visualization.quantity_support()` function will change the settings on your `matplotlib` session to better handle astropy `Quantity` objects:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "quantity_support()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can plot a histogram of the velocity dataset. Note that, due to calling `quantity_support`, the x-axis is automatically labeled with the correct units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure()\n",
    "plt.hist(v, bins='auto', histtype=\"step\")\n",
    "plt.ylabel(\"N\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can calculate the velocity dispersion of the galaxy. This demonstrates how you can perform basic operations like subtraction and division with `Quantity` objects, and also use them in standard numpy functions such as `mean()` and `size()`. They retain their units through these operations just as you would expect them to."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sigma = np.sqrt(np.sum((v - np.mean(v))**2) / np.size(v))\n",
    "print(\"Velocity dispersion: {0:.2f}\".format(sigma))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note how we needed to use `numpy` square root function, because the resulting velocity dispersion quantity is a `numpy` array. If we used the python standard `math` library's `sqrt` function instead, we get an error."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sigma_scalar = np.sqrt(np.sum((v - np.mean(v))**2) / len(v))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In general, you should only use `numpy` functions with `Quantity` objects, *not* the `math` equivalents, unless you are sure you understand the consequences."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now for the actual mass calculation.  If a galaxy is pressure-supported (for example, an elliptical or dwarf spheroidal galaxy), its mass within the stellar extent can be estimated using a straightforward formula: $M_{1/2}=4\\sigma^2 R_{eff}/G$.  There are caveats to the use of this formula for science -- see Wolf et al. 2010 for details.  For demonstrating `Quantity`, you can accept that this is often good enough. For the calculation, we can multiply the quantities together, and `astropy` will keep track of the units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "M = 4*sigma**2*Reff/G\n",
    "M"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is in a composite unit, so it's not really obvious it's a mass. However, it can be decomposed to cancel all of the length units ($km^2 pc/m^3$) using the `decompose()` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "M.decompose()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also easily express the mass in whatever form you like -- solar masses are common in astronomy, or maybe you want the default SI and CGS units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"\"\"Galaxy mass\n",
    "in solar units: {0:.3g}\n",
    "SI units: {1:.3g}\n",
    "CGS units: {2:.3g}\"\"\".format(M.to(u.Msun), M.si, M.cgs))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or, if you want the log of the mass, you can just use ``np.log10`` as long as the logarithm's argument is dimensionless."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.log10(M.to_value(u.Msun))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, you can't take the log of something with units, as that is not mathematically sensible."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [],
   "source": [
    "np.log10(M)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use `Quantity` and Kepler's law in the form given below to determine the (circular) orbital speed of the Earth around the sun in km/s. No need to look up constants or conversion factors to do this calculation -- it's all in `astropy.units` and `astropy.constants`.\n",
    "\n",
    "$$v = \\sqrt{\\frac{G M_{\\odot}}{r}}$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There's a much easier way to figure out the velocity of the Earth using just two units or quantities.  Do that and then compare to the Kepler's law answer (the easiest way is probably to compute the percentage difference, if any)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(Completely optional, but a good way to convince yourself of the value of Quantity:) Do the above calculations by hand -- you can use a calculator (or python just for its arithmatic) but look up all the appropriate conversion factors and use paper-and-pencil approaches for keeping track of them all.  Which one took longer?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Molecular cloud mass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this second example, we will demonstrate how using `Quantity` objects can facilitate a full derivation of the total mass of a molecular cloud using radio observations of isotopes of Carbon Monoxide (CO)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Setting up the data cube"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's assume that we've mapped the inner part of a molecular cloud in the J=1-0 rotational transition of ${\\rm C}^{18}{\\rm O}$  and are interested in measuring its total mass. The measurement produced a data cube with RA and Dec as spatial coordiates and velocity as the third axis. Each voxel in this data cube represents the brightness temperature of the emission at that position and velocity. Furthermore, we'll assume that we have an independent measurement of distance to the cloud $d=250$ pc and that the excitation temperature is known and constant throughout the cloud: $T_{ex}=25$ K."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "d = 250 * u.pc\n",
    "Tex = 25 * u.K"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll generate a synthetic dataset, assuming the cloud follows a Gaussian distribution in each of RA, Dec and velocity. We start by creating a 100x100x300 numpy array, such that the first coordinate is right ascension, the second is declination, and the third is velocity.  We use the `numpy.meshgrid` function to create data cubes for each of the three coordinates, and then use them in the formula for a Gaussian to generate an array with the synthetic data cube. In this cube, the cloud is positioned at the center of the cube, with $\\sigma$ and the center in each dimension shown below.  Note in particular that the $\\sigma$ for RA and Dec have different units from the center, but `astropy` automatically does the relevant conversions before computing the exponential."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Cloud's center\n",
    "cen_ra = 52.25 * u.deg\n",
    "cen_dec = 0.25 * u.deg\n",
    "cen_v = 15 * u.km/u.s\n",
    "\n",
    "# Cloud's size\n",
    "sig_ra = 3 * u.arcmin\n",
    "sig_dec = 4 * u.arcmin\n",
    "sig_v = 3 * u.km/u.s\n",
    "\n",
    "#1D coordinate quantities\n",
    "ra = np.linspace(52, 52.5, 100) * u.deg\n",
    "dec = np.linspace(0, 0.5, 100) * u.deg\n",
    "v = np.linspace(0, 30, 300) *u.km/u.s\n",
    "\n",
    "#this creates data cubes of size for each coordinate based on the dimensions of the other coordinates\n",
    "ra_cube, dec_cube, v_cube = np.meshgrid(ra, dec, v)\n",
    "\n",
    "data_gauss = np.exp(-0.5*((ra_cube-cen_ra)/sig_ra)**2 + \n",
    "                    -0.5*((dec_cube-cen_dec)/sig_dec)**2 + \n",
    "                    -0.5*((v_cube-cen_v)/sig_v)**2 )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The units of the exponential are dimensionless, so we multiply the data cube by K to get brightness temperature units. Radio astronomers use a rather odd set of units [K km/s] as of integrated intensity (that is, summing all the emission from a line over velocity). As an aside for experts, we're setting up our artificial cube on the main-beam temperature scale (T$_{\\rm MB}$) which is the closest we can normally get to the actual brightness temperature of our source."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = data_gauss * u.K"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will also need to know the width of each velocity bin and the size of each pixel, so let's calculate that now."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Average pixel size\n",
    "# This is only right if dec ~ 0, because of the cos(dec) factor.\n",
    "dra = (ra.max() - ra.min()) / len(ra)\n",
    "ddec = (dec.max() - dec.min()) / len(dec)\n",
    "\n",
    "#Average velocity bin width\n",
    "dv = (v.max() - v.min()) / len(v)\n",
    "print(\"\"\"dra = {0}\n",
    "ddec = {1}\n",
    "dv = {2}\"\"\".format(dra.to(u.arcsec), ddec.to(u.arcsec), dv))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We're interested in the integrated intensity over all of the velocity channels, so let's create a 2D quantity array by summing our data cube along the velocity axis (multiplying by the velocity width of a pixel)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "intcloud = np.sum(data*dv, axis=2)\n",
    "intcloud.unit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can plot the 2D quantity using matplotlib's imshow function, by passing the quantity's value. Similarly, we can set the correct extent using the values of $x_i$ and $x_f$. Finally, we can set the colorbar label to have proper units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Note that we display RA in the convential way by going from max to min\n",
    "plt.imshow(intcloud.value, \n",
    "           origin='lower', \n",
    "           extent=[ra.value.max(), ra.value.min(), dec.value.min(), dec.value.max()], \n",
    "           cmap='hot', \n",
    "           interpolation='nearest', \n",
    "           aspect='equal')\n",
    "plt.colorbar().set_label(\"Intensity ({})\".format(intcloud.unit))\n",
    "plt.xlabel(\"RA (deg)\")\n",
    "plt.ylabel(\"Dec (deg)\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Measuring The Column Density of CO"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In order to calculate the mass of the molecular cloud, we need to measure its column density. A number of assumptions are required for the following calculation; the most important are that the emission is optically thin (typically true for ${\\rm C}^{18}{\\rm O}$) and that conditions of local thermodynamic equilibrium hold along the line of sight. In the case where the temperature is large compared to the separation in energy levels for a molecule and the source fills the main beam of the telescope, the total column density for ${\\rm C}^{13}{\\rm O}$ is\n",
    "\n",
    "$N=C \\frac{\\int T_B(V) dV}{1-e^{-B}}$\n",
    "\n",
    "where the constants $C$ and $B$ are given by:\n",
    "\n",
    "$C=3.0\\times10^{14} \\left(\\frac{\\nu}{\\nu_{13}}\\right)^2 \\frac{A_{13}}{A} {\\rm K^{-1} cm^{-2} \\, km^{-1} \\, s}$\n",
    "\n",
    "$B=\\frac{h\\nu}{k_B T}$\n",
    "\n",
    "(Rohlfs & Wilson [Tools for Radio Astronomy](https://www.springer.com/gp/book/9783662053942)). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we have given an expression for $C$ scaled to the values for ${\\rm C}^{13}{\\rm O}$ ($\\nu_{13}$ and $A_{13}$). In order to use this relation for ${\\rm C}^{18}{\\rm O}$, we need to rescale the frequencies ${\\nu}$ and Einstein coefficients $A$. $C$ is in funny mixed units, but that's okay. We'll define it as a `Quantities` object and not have to worry about it. \n",
    "\n",
    "First, we look up the wavelength for these emission lines and store them as quantities. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lambda13 = 2.60076 * u.mm\n",
    "lambda18 = 2.73079 * u.mm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since the wavelength and frequency of light are related using the speed of light, we can convert between them. However, doing so just using the `to()` method fails, as units of length and frequency are not convertible:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [],
   "source": [
    "nu13 = lambda13.to(u.Hz)\n",
    "nu18 = lambda18.to(u.Hz)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fortunately, `astropy` comes to the rescue by providing a feature called \"unit equivalencies.\"  Equivalencies provide a way to convert between two physically different units that are not normally equivalent, but in a certain context have a one-to-one mapping.  For more on equivalencies, see the [equivalencies section of astropy's documentation](http://docs.astropy.org/en/stable/units/equivalencies.html).\n",
    "\n",
    "In this case, calling the ``astropy.units.spectral()`` function provides the equivalencies necessary to handle conversions between wavelength and frequency. To use it, provide the equivalencies to the `equivalencies` keyword of the ``to()`` call:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nu13 = lambda13.to(u.Hz, equivalencies=u.spectral())\n",
    "nu18 = lambda18.to(u.Hz, equivalencies=u.spectral())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we look up Einstein coefficients (in units of s$^{-1}$), and calculate the ratios in constant $C$. Note how the ratios of frequency and Einstein coefficient units are dimensionless, so the unit of $C$ is unchanged."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nu13 = 115271096910.13396 * u.Hz\n",
    "nu18 = 109782318669.689 * u.Hz\n",
    "A13 = 7.4e-8 / u.s\n",
    "A18 = 8.8e-8 / u.s\n",
    "\n",
    "C = 3e14 * (nu18/nu13)**3 * (A13/A18) / (u.K * u.cm**2 * u.km *(1/u.s))\n",
    "C"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we move on to calculate the constant $B$. This is given by the ratio of $\\frac{h\\nu}{k_B T}$, where $h$ is Planck's constant, $k_B$ is the Boltzmann's constant, $\\nu$ is the emission frequency, and $T$ is the excitation temperature. The constants were imported from `astropy.constants`, and the other two values are already calculated, so here we just take the ratio."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "B = h * nu18 / (k_B * Tex)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The units of $B$ are Hz sec, which can be decomposed to a dimensionless unit if you actually care about its value.  Usually this is not necessary, though. Quantities are at their best if you use them without worrying about intermediate units, and only convert at the very end when you want a final answer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('{0}\\n{1}'.format(B, B.decompose()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "At this point we have all the ingredients to calculate the number density of $\\rm CO$ molecules in this cloud. We already integrated (summed) over the velocity channels above to show the integrated intensity map, but we'll do it again here for clarity. This gives us the column density of CO for each spatial pixel in our map. We can then print out the peak column column density."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NCO = C * np.sum(data*dv, axis=2) / (1 - np.exp(-B))\n",
    "print(\"Peak CO column density: \")\n",
    "np.max(NCO)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### CO to Total Mass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are using CO as a tracer for the much more numerous H$_2$, the quantity we are actually trying to infer. Since most of the mass is in H$_2$, we calculate its column density by multiplying the CO column density with the (known/assumed) H$_2$/CO ratio."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "H2_CO_ratio = 5.9e6\n",
    "NH2 = NCO * H2_CO_ratio\n",
    "print(\"Peak H2 column density: \")\n",
    "np.max(NH2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's a peak column density of roughly 50 magnitudes of visual extinction (assuming the conversion between N$_{\\rm H_2}$ and A$_V$ from Bohlin et al. 1978), which seems reasonable for a molecular cloud."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We obtain the mass column density by multiplying the number column density by the mass of an individual H$_2$ molecule. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mH2 = 2 * 1.008 * u.Dalton  #aka atomic mass unit/amu\n",
    "rho = NH2 * mH2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A final step in going from the column density to mass is summing up over the area area. If we do this in the straightforward way of length x width of a pixel, this area is then in units of ${\\rm deg}^2$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dap = dra * ddec\n",
    "print(dap)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now comes an important subtlety: in the small angle approximation, multiplying the pixel area with the square of distance yields the cross-sectional area of the cloud that the pixel covers, in *physical* units, rather than angular units.  So it's tempting to just multiply the area and the square of the distance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "da = dap * d**2  # don't actually do it this way - use the version below instead!\n",
    "print(da)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dap.to(u.steradian).value * d**2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But this is **wrong**, because `astropy.units` treats angles (and solid angles) as actual physical units, while the small-angle approximation assumes angles are dimensionless.  So if you, e.g., try to convert to a different area unit, it will fail:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [],
   "source": [
    "da.to(u.cm**2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The solution is to use the `dimensionless_angles` equivalency, which allows angles to be treated as dimensionless.  This makes it so that they will automatically convert to radians and become dimensionless when a conversion is needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "da = (dap * d**2).to(u.pc**2, equivalencies=u.dimensionless_angles())\n",
    "da"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "da.to(u.cm**2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, multiplying the column density with the pixel area and summing over all the pixels gives us the cloud mass."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "M = np.sum(rho * da)\n",
    "M.decompose().to(u.solMass)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The astro material was pretty heavy on that one, so let's focus on some associated statistics using `Quantity`'s array capabililities. Compute the median and mean of the `data` with the ``np.mean`` and ``np.median`` functions.  Why are their values so different?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly, compute the standard deviation and variance (if you don't know the relevant functions, look it up in the numpy docs or just type np.<tab> and a code cell).  Do they have the units you expect?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Using Quantities with Functions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`Quantity` is also a useful tool if you plan to share some of your code, either with collaborators or the wider community.  By writing functions that take `Quantity` objects instead of raw numbers or arrays, you can write code that is agnostic to the input unit.  In this way, you may even be able to prevent [the destruction of Mars orbiters](http://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure). Below, we provide a simple example."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Suppose you are working on an instrument, and the person funding it asks for a function to give an analytic estimate of the response function.  You determine from some tests it's basically a Lorentzian, but with a different scale along the two axes.  Your first thought might be to do this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def response_func(xinarcsec, yinarcsec):\n",
    "    xscale = 0.9\n",
    "    yscale = 0.85\n",
    "    xfactor = 1 / (1 + xinarcsec/xscale)\n",
    "    yfactor = 1 / (1 + yinarcsec/yscale)\n",
    "    \n",
    "    return xfactor * yfactor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You meant the inputs to be in arcsec, but alas, you send that to your collaborator and they don't look closely and think the inputs are instead supposed to be in arcmin.  So they do:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response_func(1.0, 1.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And now they tell all their friends how terrible the instrument is, because it's supposed to have arcsecond resolution, but your function clearly shows it can only resolve an arcmin at best. But you can solve this by requiring they pass in `Quantity` objects.  The new function could simply be:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def response_func(x, y):\n",
    "    xscale = 0.9 * u.arcsec\n",
    "    yscale = 0.85 * u.arcsec\n",
    "    xfactor = 1 / (1 + x/xscale)\n",
    "    yfactor = 1 / (1 + y/yscale)\n",
    "    \n",
    "    return xfactor * yfactor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And your collaborator now has to pay attention.  If they just blindly put in a number they get an error:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [],
   "source": [
    "response_func(1.0, 1.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Which is their cue to provide the units explicitly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response_func(1.0*u.arcmin, 1.2*u.arcmin)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The funding agency is impressed at the resolution you achieved, and your instrument is saved!  You now go on to win the Nobel Prize due to discoveries the instrument makes.  And it was all because you used `Quantity` as the input of code you shared."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Write a function that computes the Keplerian velocity you worked out in section 1 (using `Quantity` input and outputs, of course), but allowing for an arbitrary mass and orbital radius.  Try it with some reasonable numbers for satellites orbiting the Earth, a moon of Jupiter, or an extrasolar planet.  Feel free to use wikipedia or similar for the masses and distances.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "astropy-tutorials": {
   "author": "Ana Bonaca <ana.bonaca@yale.edu>, Erik Tollerud <erik.tollerud@yale.edu>, Jonathan Foster <jonathan.b.foster@yale.edu>",
   "date": "April 2014",
   "description": "Demonstrates use of the astropy.units, astropy.constants, and the Quantity object for calculating the mass of a galaxy from its velocity dispersion and determining masses of molecular clouds from CO intensity maps. Includes use of matplotlib for making a histogram and an image with a colorbar. Also includes good practices for using quantities in functions you might distribute to other people.",
   "link_name": "Using Astropy Quantities for astrophysical calculations",
   "name": "",
   "published": true
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}